#include <stdio.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdlib.h>
#include <time.h>

#ifdef __TRUNC_LOG_ENABLED__
#define DEBUGFILE_MAXLEN 2*1024*1024
#endif

#define LOG_BUFFER_MAX_SIZE 4096

int g_fd_log = -1;

char *__yal_file__;
int  __yal_line__;

int _debug_log ( char *fmt, ... )
{
    struct stat st_stat;

    int pid = getpid();
    char sz_log_file[512] = {0};
    sprintf ( sz_log_file,"./logs/log.%06d", pid );

    if ( stat ( sz_log_file, &st_stat ) == -1 )
    {
        if ( g_fd_log >= 0 ) close ( g_fd_log );
        g_fd_log = open ( sz_log_file,O_CREAT|O_WRONLY, 0666 );
    }
#ifdef __TRUNC_LOG_ENABLED__
    else if ( st_stat.st_size > DEBUGFILE_MAXLEN )
    {
        if ( g_fd_log >= 0 ) close ( g_fd_log );
        g_fd_log = open ( sz_log_file, O_WRONLY|O_TRUNC, 0666 );
    }
#endif

    if ( g_fd_log == -1 ) return EXIT_FAILURE;

    time_t t_current_time = time ( NULL );
    struct tm st_local_time = *localtime ( &t_current_time );
    char sz_output_buffer[LOG_BUFFER_MAX_SIZE] = {0};
    sprintf ( sz_output_buffer,"<%04d_%02d_%02d %02d:%02d:%02d> \"%s\"(%d): ",
              st_local_time.tm_year + 1900, st_local_time.tm_mon + 1, st_local_time.tm_mday,
              st_local_time.tm_hour, st_local_time.tm_min, st_local_time.tm_sec,
              __yal_file__, __yal_line__ );
    write ( g_fd_log, sz_output_buffer, strlen ( sz_output_buffer ) );

    va_list ap;
    va_start ( ap, fmt );
    ( void ) vsprintf ( sz_output_buffer, fmt, ap );
    va_end ( ap );
    write ( g_fd_log, sz_output_buffer, strlen ( sz_output_buffer ) );

    write ( g_fd_log, "\n", 1 );

    return 0;
}

void close_log()
{
    close(g_fd_log);
}

